<template>
  <a-tree-select
    v-model="selectedId"
    :allow-search="allowSearch"
    :allow-clear="allowClear"
    :disabled="disable"
    :data="treeData"
    :placeholder="placeholder"
    :multiple="multiple"
    :tree-check-strictly="treeCheckStrictly"
    :selectable="selectable"
    :field-names="{
      key: 'id',
      title: 'name',
      children: 'children',
    }"
    @change="handleChangeSelector"
  ></a-tree-select>
</template>

<script lang="ts" setup>
  import { ref, defineProps, defineEmits, watch } from 'vue';
  import { TreeNodeData } from '@arco-design/web-vue/es/tree/interface';
  import useLoading from '@/hooks/loading';
  import { selectAllMenu } from '@/api/menu';
  import tree from '@/utils/tree';

  const { setLoading } = useLoading();
  const props = defineProps({
    placeholder: {
      type: String,
      default: () => {
        return '请选择菜单';
      },
    },
    // 设置可选择的节点，默认全部可选
    selectable: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    portalId: {
      type: String,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    allowSearch: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    allowClear: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
    disable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    treeCheckStrictly: {
      type: Boolean,
      default: () => {
        return true;
      },
    },
  });
  const emit = defineEmits(['update:modelValue', 'change']);
  const treeData = ref<TreeNodeData[]>([]);
  const selectedId = ref();
  const handleChangeSelector = () => {
    const arr = tree.flatTreeData(treeData.value);
    emit(
      'change',
      props.multiple
        ? arr.filter((item: any) => selectedId.value.includes(item.id))
        : arr.find((item: any) => item.id === selectedId.value)
    );
  };
  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await selectAllMenu(props.portalId);
      treeData.value = tree.toTree(data, 'id', 'parentId');
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      setLoading(false);
    }
  };
  watch(
    () => props.portalId,
    (n: string) => {
      if (n) {
        fetchData();
      } else {
        treeData.value = [];
        selectedId.value = '';
      }
    }
  );
</script>
